import { useState } from 'react'
import { CircleAlert, Download, Loader2 } from 'lucide-react'
import { IPC_CHANNELS } from 'shared/ipcChannels'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { useCurrentLiveControl } from '@/hooks/useLiveControl'
import { useAccounts } from '@/hooks/useAccounts'
import { useToast } from '@/hooks/useToast'

export default function DarenJuan() {
  const isConnected = useCurrentLiveControl(context => context.isConnected)
  const accountName = useCurrentLiveControl(context => context.accountName)
  const platform = useCurrentLiveControl(context => context.platform)
  const currentAccountId = useAccounts(state => state.currentAccountId)
  const { toast } = useToast()
  
  const [loading, setLoading] = useState(false)
  const [promotionData, setPromotionData] = useState<any>(null)

  const handleTestFetch = async () => {
    try {
      setLoading(true)
      toast.success('开始获取商品数据...')
      
      // 1. 获取推广商品列表
      const promotionsResult = await window.ipcRenderer.invoke(
        IPC_CHANNELS.darenJuan.fetchPromotions as any,
        currentAccountId
      ) as { success: boolean; data?: any; error?: string }

      if (!promotionsResult?.success) {
        throw new Error(promotionsResult?.error || '获取商品数据失败')
      }

      toast.success('商品数据获取成功，正在获取佣金率...')

      // 2. 获取佣金率数据
      const commissionResult = await window.ipcRenderer.invoke(
        IPC_CHANNELS.darenJuan.fetchCommissionRates as any,
        currentAccountId
      ) as { success: boolean; data?: any; error?: string }

      if (!commissionResult?.success) {
        // 即使佣金率获取失败，也显示商品数据
        toast.error('佣金率数据获取失败，仅显示商品基本信息')
        setPromotionData(promotionsResult.data)
        return
      }

      // 3. 合并数据：通过 product_id 关联
      const commissionMap = new Map()
      if (commissionResult.data && Array.isArray(commissionResult.data)) {
        commissionResult.data.forEach((item: any) => {
          if (item.product_id) {
            commissionMap.set(item.product_id, item)
          }
        })
      }

      // 4. 将佣金率数据合并到商品列表中
      if (promotionsResult.data?.data?.promotions) {
        promotionsResult.data.data.promotions = promotionsResult.data.data.promotions.map((item: any) => {
          const commissionData = commissionMap.get(item.product_id)
          return {
            ...item,
            commissionData, // 添加佣金率相关数据
          }
        })
      }

      setPromotionData(promotionsResult.data)
      toast.success('数据获取成功！')
    } catch (error) {
      toast.error(error instanceof Error ? error.message : '获取数据失败')
      setPromotionData(null)
    } finally {
      setLoading(false)
    }
  }

  const isDouyinPlatform = platform === 'douyin' || platform === 'buyin'

  return (
    <div className="container py-6 space-y-4">
      <div className="flex items-center gap-3 mb-4">
        <h1 className="text-xl font-semibold">达人卷</h1>
        <span className="text-sm text-muted-foreground">获取并管理抖音巨量百应的达人卷数据</span>
      </div>

      <div className="space-y-6">
        {/* 连接状态提示 */}
        {isConnected !== 'connected' && (
          <Alert>
            <CircleAlert className="h-4 w-4" />
            <AlertTitle>请先连接到直播控制台</AlertTitle>
            <AlertDescription>
              达人卷功能需要连接到抖音巨量百应控制台才能使用，请先前往「打开中控台」页面进行连接。
            </AlertDescription>
          </Alert>
        )}

        {isConnected === 'connected' && !isDouyinPlatform && (
          <Alert>
            <CircleAlert className="h-4 w-4" />
            <AlertTitle>平台不支持</AlertTitle>
            <AlertDescription>
              达人卷功能仅支持抖音和巨量百应平台，当前连接的平台为：{platform}
            </AlertDescription>
          </Alert>
        )}

        {/* 操作按钮 */}
        <div className="flex items-center justify-between mb-4">
          <div className="text-sm text-muted-foreground">
            {promotionData?.data?.promotions 
              ? `共 ${promotionData.data.promotions.length} 件商品`
              : '点击按钮获取达人卷数据'}
          </div>
          <Button
            onClick={handleTestFetch}
            disabled={isConnected !== 'connected' || !isDouyinPlatform || loading}
            size="sm"
          >
            {loading ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                获取中...
              </>
            ) : (
              <>
                <Download className="mr-2 h-4 w-4" />
                获取数据
              </>
            )}
          </Button>
        </div>

        {/* 表格 */}
        <div className="rounded-md border bg-white">
          <Table>
            <TableHeader>
              <TableRow className="bg-gray-50">
                <TableHead className="w-16">序号</TableHead>
                <TableHead className="min-w-[300px]">商品信息</TableHead>
                <TableHead className="w-24">佣金率</TableHead>
                <TableHead className="w-24">佣金</TableHead>
                <TableHead className="w-24">扣后佣金</TableHead>
                <TableHead className="w-24">利润</TableHead>
                <TableHead className="w-24">商品状态</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={7} className="h-32">
                    <div className="flex items-center justify-center">
                      <Loader2 className="h-8 w-8 animate-spin text-primary" />
                    </div>
                  </TableCell>
                </TableRow>
              ) : promotionData?.data?.promotions && promotionData.data.promotions.length > 0 ? (
                promotionData.data.promotions.map((item: any, index: number) => (
                  <TableRow key={item.promotion_id}>
                    {/* 序号 */}
                    <TableCell className="font-medium">{index + 1}</TableCell>
                    
                    {/* 商品信息 */}
                    <TableCell>
                      <div className="flex gap-3">
                        <img
                          src={item.cover}
                          alt={item.title}
                          className="w-12 h-12 object-cover rounded"
                        />
                        <div className="flex-1 min-w-0">
                          <div className="text-sm font-medium line-clamp-2 mb-1">
                            {item.title}
                          </div>
                          <div className="text-xs text-gray-500">
                            ID ¥{(item.price_desc?.min_price?.origin / 100).toFixed(2)}
                          </div>
                        </div>
                      </div>
                    </TableCell>
                    
                            {/* 佣金率 */}
                            <TableCell>
                              <span className="text-sm">
                                {item.commissionData?.commission_rate 
                                  ? `${item.commissionData.commission_rate}%` 
                                  : '-'}
                              </span>
                            </TableCell>
                            
                            {/* 佣金 */}
                            <TableCell>
                              <span className="text-sm">
                                {item.commissionData?.commission 
                                  ? `¥${(item.commissionData.commission / 100).toFixed(2)}`
                                  : '-'}
                              </span>
                            </TableCell>
                            
                            {/* 扣后佣金 */}
                            <TableCell>
                              <span className="text-sm">
                                {item.commissionData?.after_deduction_commission 
                                  ? `¥${(item.commissionData.after_deduction_commission / 100).toFixed(2)}`
                                  : '-'}
                              </span>
                            </TableCell>
                            
                            {/* 利润 */}
                            <TableCell>
                              <span className="text-sm">
                                {item.commissionData?.profit 
                                  ? `¥${(item.commissionData.profit / 100).toFixed(2)}`
                                  : '-'}
                              </span>
                            </TableCell>
                    
                    {/* 商品状态 */}
                    <TableCell>
                      <span className="text-sm text-green-600">可发券</span>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={7} className="h-32">
                    <div className="text-center text-sm text-muted-foreground">
                      暂无数据，点击"获取数据"按钮加载商品信息
                    </div>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      </div>
    </div>
  )
}
